package cn.aitrox.ry.service.image.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.Arrays;
import java.util.List;

@Configuration
public class MongoConfig {

    @Autowired
    private ImageNacosProp imageNacosProp;

    @Bean(name = "mongoTemplate")
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoDbFactory());
    }

    public MongoDbFactory mongoDbFactory() {
        return this.initMongoDbFactory(imageNacosProp.getHost1(), imageNacosProp.getPort1(),
                imageNacosProp.getHost2(), imageNacosProp.getPort2(),
                imageNacosProp.getAuthDatabase(), imageNacosProp.getUsername(), imageNacosProp.getPassword(), imageNacosProp.getDatabase());
    }

    private MongoDbFactory initMongoDbFactory(String host1, int port1, String host2, int port2, String authDatabase, String userName, String password, String useDatabase) {
        List<ServerAddress> seeds = Arrays.asList(new ServerAddress(host1, port1), new ServerAddress(host2, port2));
        List<MongoCredential> credentialsList = Arrays.asList(MongoCredential.createScramSha1Credential(userName, authDatabase, password.toCharArray()));
        return new SimpleMongoDbFactory(new MongoClient(seeds, credentialsList), useDatabase);
    }
}
